<template>
  <div class="search-results-page">
    <h2>“{{ keyword }}” 的搜索结果</h2>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="goods.length" class="goods-list">
      <div v-for="good in goods" :key="good.id" class="good-card-wrapper">
        <div class="good-card">
          <img :src="getImageUrl(good.image)" alt="商品图片" @error="handleImageError" />
          <div class="good-info">
            <h3>{{ good.name }}</h3>
            <p>价格：￥{{ good.price }}</p>
            <p>库存：{{ good.stock }}</p>
          </div>
        </div>
        <button class="buy-now-button" @click="buyNow(good)">立即购买</button>
      </div>
    </div>
    <div v-else class="no-result">没有找到相关商品</div>
  </div>
</template>

<script>
import placeholder from '@/assets/images/placeholder.jpg'
import goodApi from '@/api/controller'

export default {
  name: 'SearchResults',
  data() {
    return {
      keyword: '',
      goods: [],
      loading: true
    }
  },
  created() {
    this.keyword = this.$route.query.keyword || ''
    if (this.keyword) {
      this.fetchGoods(this.keyword)
    } else {
      this.loading = false
    }
  },
  methods: {
    async fetchGoods(keyword) {
      try {
        const response = await goodApi.getGoodListPage(1, 10, keyword)
        this.goods = response.data.list || []
      } catch (error) {
        console.error('搜索商品失败:', error)
        this.goods = []
      } finally {
        this.loading = false
      }
    },
    getImageUrl(imagePath) {
      return imagePath ? require(`@/assets/images/${imagePath}`) : placeholder
    },
    handleImageError(event) {
      event.target.src = this.getImageUrl('placeholder')
    },
    buyNow(good) {
      console.log('立即购买:', good)
      // 示例：跳转到商品详情页
      // this.$router.push({ name: 'GoodsDetail', params: { id: good.id } })
    }
  }
}
</script>

<style scoped>
.search-results-page {
  max-width: 1000px;
  margin: 60px auto;
  padding: 20px;
}

.goods-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.good-card-wrapper {
  text-align: center;
  margin-bottom: 20px;
}

.good-card {
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 15px;
  background-color: #fff;
  text-align: center;
  transition: box-shadow 0.3s;
}

.good-card:hover {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.good-card img {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}

.good-info h3 {
  font-size: 16px;
  margin: 5px 0;
}

.good-info p {
  margin: 4px 0;
  color: #666;
}

.buy-now-button {
  background-color: red; /* 设置按钮背景色为红色 */
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
  margin-top: 10px;
  font-size: 16px; /* 可选：增大字体大小 */
}

.buy-now-button:hover {
  background-color: darkred; /* 鼠标悬停时的颜色 */
}

.loading,
.no-result {
  text-align: center;
  padding: 40px;
  font-size: 16px;
  color: #999;
}
</style>